package com.davy.tx;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;

import androidx.core.app.ActivityCompat;
import androidx.multidex.MultiDex;

import com.davy.tx.http.CommonHttpUtil;
import com.davy.tx.http.HttpClient;
import com.davy.tx.http.SSLSocketClient;
import com.davy.tx.utils.GPSToGCJ;
import com.davy.tx.utils.LogUtils;
import com.davy.tx.utils.SPUtils;
import com.davy.tx.utils.StringUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cookie.CookieJarImpl;
import com.lzy.okgo.cookie.store.SPCookieStore;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;
import com.lzy.okgo.model.HttpHeaders;
import com.tencent.qcloud.tuicore.TUIConstants;
import com.tencent.qcloud.tuicore.TUICore;
import com.tencent.qcloud.tuicore.interfaces.ITUINotification;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import okhttp3.OkHttpClient;


public class DavyTx extends Application {
    private static Application mContext;
    protected static LocationManager locationManager;
    protected static LocationListener locationListener;
    public static String mLongitude, mLatitude, mAltitude;
    protected static DecimalFormat decimalFormat;
    public static String railway = "gongju";

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
        MultiDex.install(this);
        locationUpdatesActive = false;
        LogUtils.setIsDebug(true);
        CommonHttpUtil.init();
        decimalFormat = new DecimalFormat("#.000000");
        initLocation();
        //---------这里给出的是示例代码,告诉你可以这么传,实际使用的时候,根据需要传,不需要就不传-------------//
        HttpHeaders headers = new HttpHeaders();
//        headers.put("Content-Type", "text/plain");
        headers.put("Content-Type", "application/json");     //header不支持中文，不允许有特殊字符
        headers.put("dateType", "json");
        headers.put("charset", "UTF-8");
//        HttpParams params = new HttpParams();
//        params.put("Content-Type", "application/json");
//        params.put("dateType", "json"); //param支持中文,直接传,不要自己编码
//        params.put("charset", "UTF-8");
        //-----------------------------------------------------------------------------------//

        //构建OkHttpClient.Builder
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.sslSocketFactory(SSLSocketClient.getSSLSocketFactory());
        builder.hostnameVerifier(SSLSocketClient.getHostnameVerifier());

        //配置log打印级别
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
        //log打印级别，决定了log显示的详细程度
        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
//        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.NONE);
        //log颜色级别，决定了log在控制台显示的颜色
        loggingInterceptor.setColorLevel(Level.INFO);
        builder.addInterceptor(loggingInterceptor);

        //全局的读取超时时间
        builder.readTimeout(HttpClient.TIMEOUT, TimeUnit.MILLISECONDS);
        //全局的写入超时时间
        builder.writeTimeout(HttpClient.TIMEOUT, TimeUnit.MILLISECONDS);
        //链接超时时间
        builder.connectTimeout(HttpClient.TIMEOUT, TimeUnit.MILLISECONDS);

        //使用sp保持cookie，如果cookie不过期，则一直有效
        builder.cookieJar(new CookieJarImpl(new SPCookieStore(this)));

        //以下设置的所有参数是全局参数,同样的参数可以在请求的时候再设置一遍,那么对于该请求来讲,请求中的参数会覆盖全局参数
        //好处是全局参数统一,特定请求可以特别定制参数
        try {
            OkGo.getInstance().init(this)//必须调用初始化

                    //以下都不是必须的，根据需要自行选择
                    .setOkHttpClient(builder.build())
                    //可以全局统一设置缓存模式,默认是不使用缓存,可以不传,具体其他模式看 github 介绍 https://github.com/jeasonlzy/
//                    .setCacheMode(CacheMode.NO_CACHE)
                    //可以全局统一设置缓存时间,默认永不过期,具体使用方法看 github 介绍
//                    .setCacheTime(7)
                    //可以全局统一设置超时重连次数,默认为三次,那么最差的情况会请求4次(一次原始请求,三次重连请求),不需要可以设置为0
                    .setRetryCount(0)
                    //这两行同上，不需要就不要加入
                    .addCommonHeaders(headers);   //设置全局公共头
//                    .addCommonParams(params);   //设置全局公共参数
        } catch (Exception e) {
            e.printStackTrace();
        }

        Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler(getContext()));

        StrictMode.VmPolicy.Builder builder1 = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder1.build());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            builder1.detectFileUriExposure();
        }
        closeAndroidPDialog();

        configFCMPrivateRing();

        registerActivityLifecycleCallbacks();
    }

    private void configFCMPrivateRing() {
        TUICore.registerEvent(TUIConstants.TIMPush.EVENT_IM_LOGIN_AFTER_APP_WAKEUP_KEY, TUIConstants.TIMPush.EVENT_IM_LOGIN_AFTER_APP_WAKEUP_SUB_KEY, new ITUINotification() {
            @Override
            public void onNotifyEvent(String key, String subKey, Map<String, Object> param) {
                if (TUIConstants.TIMPush.EVENT_IM_LOGIN_AFTER_APP_WAKEUP_KEY.equals(key) && TUIConstants.TIMPush.EVENT_IM_LOGIN_AFTER_APP_WAKEUP_SUB_KEY.equals(subKey)) {
                    //you need to login again to launch call activity, please implement this method by yourself
                    //autoLogin();
                }
            }
        });
    }

    private void closeAndroidPDialog() {
        try {
            Class aClass = Class.forName("android.content.pm.PackageParser$Package");
            Constructor declaredConstructor = aClass.getDeclaredConstructor(String.class);
            declaredConstructor.setAccessible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            Class cls = Class.forName("android.app.ActivityThread");
            Method declaredMethod = cls.getDeclaredMethod("currentActivityThread");
            declaredMethod.setAccessible(true);
            Object activityThread = declaredMethod.invoke(null);
            @SuppressLint("SoonBlockedPrivateApi") Field mHiddenApiWarningShown = cls.getDeclaredField("mHiddenApiWarningShown");
            mHiddenApiWarningShown.setAccessible(true);
            mHiddenApiWarningShown.setBoolean(activityThread, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String mLong = "";
    private static String mLat = "";


    private static class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {

        private Context context;

        public MyUncaughtExceptionHandler(Context context) {
            this.context = context;
        }

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            // 收集设备信息、崩溃信息等
            // 可以将信息保存到文件或发送到服务器
            // 重启应用或者结束进程等
            // 注意：不要在这里处理UI操作，因为程序已经崩溃
            LogUtils.e("TAG", "e.getMessage():" + e.getMessage());
            LogUtils.e("TAG", "e.toString():" + e.toString());
            LogUtils.e("TAG", "e.getLocalizedMessage():" + e.getLocalizedMessage());

            SPUtils.put(getContext(), "benE", e.toString());
            SPUtils.put(getContext(), "benS", StringUtils.getTimeS());
        }
    }

    private void initLocation() {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                // 使用经纬度
                mLongitude = decimalFormat.format(location.getLongitude());
                mLatitude = decimalFormat.format(location.getLatitude());
                mAltitude = decimalFormat.format(location.getAltitude()); // 获取海拔高度

                LogUtils.v("TAG", "经纬度：" + mLongitude + " " + mLatitude + " " + mAltitude);

                GPSToGCJ.getAddress(location);
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
            }

            @Override
            public void onProviderEnabled(String provider) {
                // 用户启用GPS时调用
                LogUtils.v("TAG", "onProviderEnabled：" + provider);
            }

            @Override
            public void onProviderDisabled(String provider) {
                // 用户禁用GPS时调用
                LogUtils.v("TAG", "onProviderDisabled：" + provider);
            }
        };

        locationUpdates();
    }

    public static void locationUpdates() {
        // 检查权限和服务是否可用
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                LogUtils.v("TAG", "有没有权限");
                return;
            }
            LogUtils.v("TAG", "有权限，开始吧");
            //LocationManager.NETWORK_PROVIDER  网络
            //LocationManager.GPS_PROVIDER  GPS
//            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3000, 3, locationListener);
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 3, locationListener);
            locationUpdatesActive = true;
        } else {
            LogUtils.v("TAG", "GPS is disabled");
            locationUpdatesActive = false;
        }
    }

    // 用于标记请求是否处于活动状态
    public static boolean locationUpdatesActive = false;

    public static Application getContext() {
        return mContext;
    }

    public static boolean isOnActivityStopped = false;

    private void registerActivityLifecycleCallbacks() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                LogUtils.e("TAG", "onActivityCreated: " + activity.getLocalClassName());
            }

            @Override
            public void onActivityStarted(Activity activity) {
                LogUtils.e("TAG", "onActivityStarted: " + activity.getLocalClassName());
                DavyTx.locationUpdates();
            }

            @Override
            public void onActivityResumed(Activity activity) {
                isOnActivityStopped = true;
                LogUtils.e("TAG", "onActivityResumed: " + activity.getLocalClassName());
            }

            @Override
            public void onActivityPaused(Activity activity) {
                LogUtils.e("TAG", "onActivityPaused: " + activity.getLocalClassName());
            }

            @Override
            public void onActivityStopped(Activity activity) {
                isOnActivityStopped = false;
                LogUtils.e("TAG", "onActivityStopped: " + activity.getLocalClassName());
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                LogUtils.e("TAG", "onActivityDestroyed: " + activity.getLocalClassName());
                if (locationManager != null && locationListener != null) {
                    locationManager.removeUpdates(locationListener);
                }
            }
        });
    }
}
